import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"

interface ProductDetailState {
	loading: boolean
	error: string | null
	data: any
}

const initialState: ProductDetailState = {
	loading: true,
	error: null,
	data: null,
}

export const getProductDetail = createAsyncThunk("productDetail/getProductDetail", async (touristRouteID: string, thunkAPI) => {
	return axios.get(`/productCollections/${touristRouteID}`)
	// axios
	// 	.get("/productCollections")
	// 	.then(res => {
	// 		console.log("productCollections ==> res: ", res)
	// 		thunkAPI.dispatch(productDetailSlice.actions.fetchSuccess(res.data))
	// 	})
	// 	.catch(err => {
	// 		console.log("productCollections ==> err: ", err)
	// 	})
})

export const productDetailSlice = createSlice({
	name: "productDetail",
	initialState,
	reducers: {
		fetchStart: state => {
			state.data = true
		},
		fetchSuccess: (state, action) => {
			state.loading = false
			state.data = action.payload
			state.error = null
		},
		fetchFailed: (state, action: PayloadAction<string | null>) => {
			state.loading = false
			state.error = action.payload
		},
	},

	extraReducers: {
		[getProductDetail.pending.type]: state => {
			state.loading = true
		},
		[getProductDetail.fulfilled.type]: (state, action) => {
			state.loading = false
			state.data = action.payload
			state.error = null
		},
		[getProductDetail.rejected.type]: (state, action: PayloadAction<string | null>) => {
			state.loading = false
			state.error = action.payload
		},
	},
})
